package cn.schoolwow.ams.module.config.handler;

import cn.schoolwow.ams.module.config.domain.QuickAMSException;
import cn.schoolwow.ams.module.initial.domain.InitialAMSContext;
import cn.schoolwow.ams.module.initial.service.InitialAMSContextCompositeBusiness;
import cn.schoolwow.quickflow.QuickFlowBuilder;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.dto.FlowContextDataRange;
import cn.schoolwow.quickflow.listener.TryCatchFinallyHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

public class AMSTryCatchFinallyHandler implements TryCatchFinallyHandler {
    @Override
    public void handleTryStart(FlowContext flowContext) throws Exception {
        ApplicationContext applicationContext = flowContext.checkInstanceData(ApplicationContext.class);

        synchronized (flowContext.getQuickFlow()){
            if(!flowContext.containInstanceKey(InitialAMSContext.class)){
                InitialAMSContext initialAMSContext = QuickFlowBuilder.startFlow(new InitialAMSContextCompositeBusiness())
                        .putTemporaryInstanceData(applicationContext, ApplicationContext.class)
                        .putTemporaryInstanceData(applicationContext.getEnvironment(), Environment.class)
                        .execute()
                        .checkInstanceData(InitialAMSContext.class);
                flowContext.putContextTemporaryInstanceData(initialAMSContext);
            }
        }
    }

    @Override
    public void handleTryEnd(FlowContext flowContext) throws Exception {

    }

    @Override
    public void handleException(FlowContext flowContext, Exception e) {
        throw new QuickAMSException(e);
    }

    @Override
    public void handleFinally(FlowContext flowContext) {

    }

    @Override
    public String name() {
        return "QuickAMS全局处理";
    }
}
